package net.melon.product.inst.service.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import net.esj.basic.core.view.tools.ActionContext;
import net.esj.basic.dao.jdbc.JdbcDao;
import net.esj.basic.exception.MelonException;
import net.esj.basic.exception.MelonRuntimeException;
import net.esj.basic.service.impl.DefaultServiceImpl;
import net.esj.basic.utils.Assert;
import net.melon.jdbc.core.RowMapper;
import net.melon.product.inst.service.ClassifyService;
import net.melon.product.inst.service.ProductService;
import net.melon.product.pojo.ProductClassify;
import net.melon.product.pojo.ProductType;
import net.melon.uploader.Uploader;
import net.melon.uploader.pojo.FileUpload;
import net.melon.uploader.service.impl.DateSplitPathRule;
import net.melon.uploader.service.impl.RandomFileNameRule;

import org.springframework.stereotype.Service;


@Service("classifyService")
public class ClassifyServiceImpl extends DefaultServiceImpl implements ClassifyService {

	private static final String LIST_CLASSIFY_SQL = "SELECT c.*,t.NAME t_NAME,t.SUB_NAME,t.STATE t_STATE FROM ML_PRODUCT_CLASSIFY c , ML_PRODUCT_TYPE t WHERE c.TYPE = t.ID ";
	
	@Resource
	private ProductService productService;

	@Override
	public List<ProductClassify> getProductClassifyList(Object[] objectArr) {
		StringBuffer sb = new StringBuffer(LIST_CLASSIFY_SQL);
		for(int i=0; i < objectArr.length; i++){
			if(objectArr.length==1){
				sb.append(" AND c.STATE in ( " + objectArr[i].toString() + ") ORDER BY `ORDER` ASC ");
			}else{
				if(i==0){
					sb.append(" AND c.STATE in ( " + objectArr[i].toString());
				}else if(i==objectArr.length-1){
					sb.append(","+objectArr[i].toString()+")  ORDER BY `ORDER` ASC ");
				}else{
					sb.append(","+objectArr[i].toString());
				}
			}
		}
		List<ProductClassify> list = getDao(JdbcDao.class).getJdbcTemplate().query(sb.toString(),
				new RowMapper<ProductClassify>() {
					@Override
					public ProductClassify mapRow(ResultSet arg0, int arg1)
							throws SQLException {
						ProductClassify bc = new ProductClassify();
						bc.setId(arg0.getLong("ID"));
						bc.setName(arg0.getString("NAME"));
						bc.setIcon(arg0.getString("ICON"));
						bc.setState(arg0.getInt("STATE"));
						bc.setOrder(arg0.getInt("ORDER"));
						bc.setLevel(arg0.getInt("LEVEL"));
						ProductType type = new ProductType();
						type.setId(arg0.getLong("TYPE"));
						type.setName(arg0.getString("t_NAME"));
						type.setSubName(arg0.getString("SUB_NAME"));
						bc.setType(type);
						Long pa = arg0.getLong("PARENT");
						if (pa != 0) {
							ProductClassify parent = new ProductClassify();
							parent.setId(pa);
							bc.setParent(parent);
						}
						return bc;
					}
				});
		
		return list;
	}
	
	
	private static final String INSERT_CLASSIFY_SQL = "INSERT INTO ML_PRODUCT_CLASSIFY(NAME,PARENT,STATE,`ORDER`,ICON,TYPE,LEVEL) VALUES (?,?,?,?,?,?,?)";
	
	@Override
	public ProductClassify saveClassify(ProductClassify classify) {
		
		try {
			Uploader uploader = new Uploader(new DateSplitPathRule(), new RandomFileNameRule(), ProductClassify.ICON_SUB_DIR);
			uploader.setAllowFiles(Uploader.ALLOW_FILE_IMAGES);
			List<FileUpload> list = uploader.upload((HttpServletRequest)ActionContext.getRequest());
			if(!list.isEmpty()){
				FileUpload up = list.get(0);
				classify.setIcon(up.getUrl());
			}
		} catch (Exception e) {
			throw new MelonRuntimeException(e);
		}
		getDao(JdbcDao.class).getJdbcTemplate().update(
				INSERT_CLASSIFY_SQL,
				new Object[] {
						classify.getName(),
						classify.getParent() == null ? null : classify
								.getParent().getId(), 
						classify.getState(),
						classify.getOrder(),
						classify.getIcon(),
						classify.getType().getId(),
						classify.getLevel()
						},
				new int[] { Types.VARCHAR, Types.BIGINT, Types.INTEGER,Types.INTEGER,Types.VARCHAR, Types.BIGINT,Types.INTEGER });
		
		return classify;
	}

	private static final String UPDATE_CLASSIFY_SQL = "UPDATE ML_PRODUCT_CLASSIFY SET NAME = ? ,STATE = ?,ICON=?,`ORDER`=?,`TYPE`=? WHERE ID = ?";

	@Override
	public ProductClassify updateClassify(ProductClassify classify) {
		
		try {
			Uploader uploader = new Uploader(new DateSplitPathRule(), new RandomFileNameRule(), ProductClassify.ICON_SUB_DIR);
			uploader.setAllowFiles(Uploader.ALLOW_FILE_IMAGES);
			List<FileUpload> list = uploader.upload((HttpServletRequest)ActionContext.getRequest());
			if(!list.isEmpty()){
				FileUpload up = list.get(0);
				classify.setIcon(up.getUrl());
			}
		} catch (Exception e) {
			throw new MelonRuntimeException(e);
		}
		
		getDao(JdbcDao.class).getJdbcTemplate().update(
				UPDATE_CLASSIFY_SQL,
				new Object[] { classify.getName(),classify.getState(), 
						classify.getIcon(),classify.getOrder(),classify.getType().getId(),classify.getId() },
				new int[] { Types.VARCHAR, Types.INTEGER,Types.VARCHAR,
						Types.INTEGER,Types.BIGINT ,Types.BIGINT});
		return classify;
	}

	private static final String SELECT_CLASSIFY_SQL = "SELECT c.*,t.NAME t_NAME,t.SUB_NAME,t.STATE t_STATE FROM ML_PRODUCT_CLASSIFY c , ML_PRODUCT_TYPE t WHERE c.TYPE = t.ID AND c.ID = ? ";

	@Override
	public ProductClassify getClassify(Long id) {
		Assert.notNull(id);
		try {
			ProductClassify bc = getDao(JdbcDao.class).getJdbcTemplate().queryForObject(
					SELECT_CLASSIFY_SQL, new RowMapper<ProductClassify>() {
						@Override
						public ProductClassify mapRow(ResultSet arg0, int arg1)
								throws SQLException {
							ProductClassify bc = new ProductClassify();
							bc.setId(arg0.getLong("ID"));
							bc.setName(arg0.getString("NAME"));
							bc.setIcon(arg0.getString("ICON"));
							bc.setState(arg0.getInt("STATE"));
							bc.setOrder(arg0.getInt("ORDER"));
							ProductType type = new ProductType();
							type.setId(arg0.getLong("TYPE"));
							type.setName(arg0.getString("t_NAME"));
							type.setSubName(arg0.getString("SUB_NAME"));
							bc.setType(type);
							Long pa = arg0.getLong("PARENT");
							if (pa != 0) {
								ProductClassify parent = new ProductClassify();
								parent.setId(pa);
								bc.setParent(parent);
							}
							return bc;
						}
					}, new Object[] { id }, new int[] { Types.INTEGER });
			return bc;
		} catch (Exception e) {
			return null;
		}
	}
	
	private static final String DELETE_CLASSIFY_SQL = "UPDATE ML_PRODUCT_CLASSIFY SET STATE = -1 WHERE ID = ?";
	
	@Override
	public void deleteClassify(Long id) throws MelonException {
		getDao(JdbcDao.class).getJdbcTemplate().update(DELETE_CLASSIFY_SQL, new Object[] { id },
				new int[] { Types.BIGINT });
	}

	@Override
	public boolean checkDeleteClassify(Long id) {
		if(productService.getProductCountByClassify(id)==0){
			return true;
		}
		return false;
	}

}
